#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#define PRO_BUFF 20
#define CONS_BUFF 0
int my_buff[PRO_BUFF];
sem_t productor_sem;
sem_t consumer_sem;
sem_t cons_comm;
sem_t pro_comm;

void*productor(void *arg)
{
	pthread_detach(pthread_self());
	int p=0;
	while(1)
	{
		sem_wait(&productor_sem);
		sem_wait(&pro_comm);
		int value=rand()%100;
		my_buff[p]=value;
		printf("productor%dalready :%d\n",(int)arg,value);
		sem_post(&pro_comm);
		sem_post(&consumer_sem);
		p=(p+1)%PRO_BUFF;
		sleep(rand()%3);
	}
}
void*consumer(void *arg)
{
	pthread_detach(pthread_self());
	int c=0;
	while(1)
	{
		sem_wait(&consumer_sem);
		sem_wait(&cons_comm);
		int value=my_buff[c];
		printf("consumer%dreceive value :%d\n",(int)arg,value);
		sem_post(&cons_comm);
		sem_post(&productor_sem);
		c=(c+1)%PRO_BUFF;
		sleep(rand()%5);
	}

}


int main()
{
	sem_init(&productor_sem,0,PRO_BUFF);
	sem_init(&consumer_sem,0,CONS_BUFF);
	sem_init(&cons_comm,0,1);
	sem_init(&pro_comm,0,1);
	pthread_t productor1_id;
	pthread_t consumer1_id;
	int i;
	for(i=1;i<4;i++)
	{
		pthread_create(&productor1_id,NULL,productor,(void*)i);

	}
	for(i=1;i<4;i++)
	{
		pthread_create(&consumer1_id,NULL,consumer,(void*)i);
	}
	pthread_join(productor1_id,NULL);
	pthread_join(consumer1_id,NULL);
}
